import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'

interface Device {
  id: string
  name: string
  type: string
  status: 'online' | 'offline' | 'maintenance'
  location: string
  lastUpdate: string
  parameters: Record<string, any>
}

interface DevicesState {
  devices: Device[]
  loading: boolean
  error: string | null
  selectedDevice: Device | null
}

const initialState: DevicesState = {
  devices: [],
  loading: false,
  error: null,
  selectedDevice: null,
}

export const fetchDevices = createAsyncThunk(
  'devices/fetchDevices',
  async () => {
    const response = await axios.get('/api/devices')
    return response.data
  }
)

export const updateDevice = createAsyncThunk(
  'devices/updateDevice',
  async ({ id, data }: { id: string; data: Partial<Device> }) => {
    const response = await axios.put(`/api/devices/${id}`, data)
    return response.data
  }
)

const devicesSlice = createSlice({
  name: 'devices',
  initialState,
  reducers: {
    selectDevice: (state, action) => {
      state.selectedDevice = action.payload
    },
    updateDeviceStatus: (state, action) => {
      const { id, status } = action.payload
      const device = state.devices.find(d => d.id === id)
      if (device) {
        device.status = status
        device.lastUpdate = new Date().toISOString()
      }
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchDevices.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchDevices.fulfilled, (state, action) => {
        state.loading = false
        state.devices = action.payload
      })
      .addCase(fetchDevices.rejected, (state, action) => {
        state.loading = false
        state.error = action.error.message || '获取设备数据失败'
      })
      .addCase(updateDevice.fulfilled, (state, action) => {
        const index = state.devices.findIndex(d => d.id === action.payload.id)
        if (index !== -1) {
          state.devices[index] = action.payload
        }
      })
  },
})

export const { selectDevice, updateDeviceStatus } = devicesSlice.actions
export default devicesSlice.reducer